package com.example.demo.controller;

import com.example.demo.dto.PaginationDTO;
import com.example.demo.mapper.UserMapper;
import com.example.demo.model.User;
import com.example.demo.server.QuestionService;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;

/***
 * 个人问题
 * 2021.7.16
 */
@Controller
public class ProfileController {

    @Autowired(required = true)
    private QuestionService mQuestionService;
    @Autowired
    private UserMapper userMapper;

    @GetMapping("/profile/{action}")// 类似传参数
//    public String profile() {
    public String profile(
            HttpServletRequest request,
            @PathVariable(name = "action") String action, Model model,
            @RequestParam(name = "page", defaultValue = "1") Integer page,
//    每页展示默认5条数
            @RequestParam(name = "size", defaultValue = "2") Integer size
    ) {
//  如果传递过来的而标签体相等把标题我的问题传入model  前端显示
        System.out.println("/进profile");

        Cookie[] cookies = request.getCookies();
        User user = null;
        if (cookies != null && cookies.length > 0) {// 判断cookies  不为null
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("token")) {
                    String token = cookie.getValue();
                    user = userMapper.findByToken(token);
                    if (user != null) {
                        request.getSession().setAttribute("user", user);
                    }
                    break;
                }

            }
        }
        if (user == null) {
//            return  "index";
            return "redirect：/";
        }

        if ("questions".equals(action)) {
            model.addAttribute("section", "questions");
            model.addAttribute("sectionName", "我的提问");
        } else if ("replies".equals(action)) {
            model.addAttribute("section", "replies");
            model.addAttribute("sectionName", "最新回复！");
        }
        System.out.println("/出/profile");
       int  userid=6;
//        page=1;
//        size=1;
        PaginationDTO pagination= mQuestionService.listbyUserId(userid, page, size);
        model.addAttribute("pagination",pagination);
        System.out.println("pagination"+pagination);
        return "profile";
    }


}
